import os
import sys
import configparser
from loguru import logger
from dotenv import load_dotenv
import redis
# 项目根目录
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))

# 配置文件路径映射
config_files = {
    "prod": os.path.join(ROOT_DIR, 'config_master.ini'),
    "dev": os.path.join(ROOT_DIR, 'config_dev.ini'),
    "test": os.path.join(ROOT_DIR, 'config_test.ini'),
    "check": os.path.join(ROOT_DIR, 'config_check.ini'),
    "demo": os.path.join(ROOT_DIR, 'config_demo.ini')
}

env_file_path = os.path.join(ROOT_DIR, '.env')  # 环境变量文件路径

# 配置文件路径映射
ENV_SECTION_MAP = {
    "dev": "DEV",
    "test": "TEST",
    "check": "CHECK",
    "demo": "DEMO",
    "prod": "PROD"
}


# 配置读取工具函数
def get_config_value(section, key, value_type='string'):
    """ 获取配置文件的配置项，提供类型转换。"""
    try:
        if value_type == 'string':
            return config.get(section, key)
        elif value_type == 'int':
            return config.getint(section, key)
        elif value_type == 'float':
            return config.getfloat(section, key)
        elif value_type == 'bool':
            return config.getboolean(section, key)
    except (configparser.NoOptionError, configparser.NoSectionError) as e:
        logger.error(f"配置项 {key} 在 {section} 中未找到: {str(e)}")
        raise


# 读取环境变量
load_dotenv(dotenv_path=env_file_path, override=True)
logger.info("环境变量已加载。")

# 获取当前环境并检查有效性
environment = os.getenv("ENVIRONMENT").lower()
if environment not in ENV_SECTION_MAP:
    raise ValueError(f"无效的环境配置: {environment}. 请检查环境变量 'ENVIRONMENT' 设置。")

section = ENV_SECTION_MAP[environment]  # 获取配置文件中的配置部分

# 根据环境变量选择对应的配置文件
config_file = config_files.get(environment)
if not os.path.exists(config_file):
    raise FileNotFoundError(f"配置文件不存在，请检查{config_file}文件是否存在。")

logger.info(f"使用的配置部分: {section}，配置文件: {config_file}")

# 读取配置文件
config = configparser.ConfigParser()
config.read(config_file, encoding='utf-8')
logger.info(f"已加载配置文件: {config_file}")

# 设置loguru日志级别
loguru_level = get_config_value(section, "LOG_LEVEL")


# 配置loguru日志记录
def configure_logging():
    """ 配置loguru日志记录器 """
    logger.remove()  # 移除默认的日志记录器

    # 控制台输出配置
    logger.add(
        sys.stdout,
        level=loguru_level,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | "
               "<level>{message}</level> | <yellow>{file}:{line}</yellow>",
        colorize=True,
        enqueue=True,
        backtrace=True,
        diagnose=True,
    )

    # 详细日志文件输出配置
    logger.add(
        os.path.join(ROOT_DIR, "output_logs", "{time:YYYY-MM-DD}.log"),
        rotation="1 day",
        retention="10 days",
        level="DEBUG",
        format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {file}:{function}:{line} - {message}",
        enqueue=True,
        backtrace=True,
        diagnose=True
    )

    # 错误日志单独保存
    logger.add(
        os.path.join(ROOT_DIR, "output_logs", "errors.log"),
        level="ERROR",
        rotation="1 week",
        retention="1 month",
        format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {file}:{function}:{line} - {message}\n{exception}",
        enqueue=True,
        backtrace=True,
        diagnose=True
    )


# 配置日志
configure_logging()

# 常量配置（可以通过配置文件或环境变量进一步优化）
TEMP_USER_VOICE_FOLDER = os.path.join(ROOT_DIR, "temp_user_voice")
USER_VOICE_FOLDER = os.path.join(ROOT_DIR, "user_voice")
MODEL_PATH = os.path.join(ROOT_DIR, "pretrained_models", "CosyVoice-300M")
demo_audio_dir = os.path.join(ROOT_DIR, 'demo_audio')

# 阿里云OSS配置
OSS_ACCESS_KEY_ID = get_config_value('OSS', 'OSS_ACCESS_KEY_ID')
OSS_ACCESS_KEY_SECRET = get_config_value('OSS', 'OSS_ACCESS_KEY_SECRET')
OSS_BUCKET_NAME = get_config_value('OSS', 'OSS_BUCKET_NAME')
OSS_ENDPOINT = get_config_value('OSS', 'OSS_ENDPOINT')
OSS_CDN_DOMAIN_NAME = get_config_value('OSS', 'OSS_CDN_DOMAIN_NAME')

# 试听音频的文本内容
DEMO_AUDIO_TEXT = '你好，我是你的一号魂体，欢迎来到MarsX音乐元宇宙世界。'

# 试听音频上传到OSS后所在的目录
DEMO_AUDIO_OSS_DIR = get_config_value(section, 'DEMO_AUDIO_OSS_DIR')

# 克隆音色任务类型
clone_task_type = "clone"

# 配置音频参数
max_val = 0.8  # 音频归一化最大值
prompt_sr, target_sr = 16000, 22050  # 音频采样率配置

# 配置端口
generate_audio_port = get_config_value(section, "TTS_PORT", "int")
timbre_clone_port = get_config_value(section, "VOICE_CLONE_PORT", "int")
worker_num = get_config_value(section, "WORKER_NUM", "int")

# 语音合成接口配置
tts_host = get_config_value(section, "TTS_HOST")
tts_protocol = get_config_value(section, "TTS_PROTOCOL")

# MySQL配置
MYSQL_HOST = get_config_value(section, 'MYSQL_HOST')
MYSQL_USER = get_config_value(section, 'MYSQL_USER')
MYSQL_PASSWORD = get_config_value(section, 'MYSQL_PASSWORD')
MYSQL_DATABASE = get_config_value(section, 'MYSQL_DATABASE')
MYSQL_PORT = get_config_value(section, 'MYSQL_PORT', 'int')

# Redis配置
REDIS_HOST = get_config_value(section, 'REDIS_HOST')
REDIS_DB = get_config_value(section, 'REDIS_DB', 'int')

# 随机种子
RANDOM_SEED = 0

# 每个任务的预计耗时(秒)
AVERAGE_TASK_DURATION = 30

# httpx 请求默认超时时间（秒）
HTTPX_DEFAULT_TIMEOUT = 300.0

# SQLAlchemy数据库URI
SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}?charset=utf8mb4"

# JWT配置
SECRET_KEY = get_config_value(section, 'SECRET_KEY')
ALGORITHM = get_config_value(section, 'ALGORITHM')

# Go服务秘钥
GO_SERVICE_SECRET_KEY = get_config_value(section, 'GO_SERVICE_SECRET_KEY')

# 在应用启动时初始化Redis客户端
redis_pool = redis.ConnectionPool(
    host=REDIS_HOST,
    port=6379,
    db=REDIS_DB,
    max_connections=10,
    socket_keepalive=True,
    retry_on_timeout=True,
    socket_timeout=10
)
global_redis_client = redis.Redis(
    connection_pool=redis_pool,
    health_check_interval=30,
    socket_keepalive=True
)
